package com.letao.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.letao.common.pojo.EUDataGridResult;
import com.letao.common.pojo.LetaoResult;
import com.letao.common.utils.IDUtils;
import com.letao.mapper.TbItemDescMapper;
import com.letao.mapper.TbItemMapper;
import com.letao.mapper.TbItemParamItemMapper;
import com.letao.pojo.TbItem;
import com.letao.pojo.TbItemDesc;
import com.letao.pojo.TbItemExample;
import com.letao.pojo.TbItemParamItem;
import com.letao.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by ac on 2017/1/9.
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private TbItemDescMapper itemDescMapper;

    @Autowired
    private TbItemParamItemMapper itemParamItemMapper;

    @Override
    public TbItem findItemByID(long itemID) {
        return tbItemMapper.selectByPrimaryKey(itemID);
    }

    @Override
    public EUDataGridResult getItemList(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        TbItemExample tbItemExample = new TbItemExample();
        List<TbItem> list = tbItemMapper.selectByExample(tbItemExample);
        //获取分页信息
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        return new EUDataGridResult(pageInfo.getTotal(), list);
    }

    @Override
    public LetaoResult createItem(TbItem item, String desc, String paramData) {
        long itemId = IDUtils.genItemId();
        item.setId(itemId);
        item.setUpdated(new Date());
        item.setCreated(new Date());
        item.setStatus((byte) 1);
        LetaoResult result = this.insertItemDesc(itemId, desc);
        if(result.getStatus() != 200){
            throw new RuntimeException("添加商品失败");
        }
         result = this.insertItemPara(itemId, paramData);
        if(result.getStatus() != 200){
            throw new RuntimeException("添加商品失败");
        }
        tbItemMapper.insert(item);
        return LetaoResult.ok();
    }

    private LetaoResult insertItemDesc(Long itemId, String desc){
        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setCreated(new Date());
        tbItemDesc.setUpdated(new Date());
        tbItemDesc.setItemDesc(desc);
        tbItemDesc.setItemId(itemId);
        itemDescMapper.insert(tbItemDesc);
        return LetaoResult.ok();
    }

    private LetaoResult insertItemPara(Long itemId, String para){
        TbItemParamItem record = new TbItemParamItem();
        record.setCreated(new Date());
        record.setUpdated(new Date());
        record.setParamData(para);
        record.setItemId(itemId);
        itemParamItemMapper.insert(record);
        return LetaoResult.ok();
    }
}